import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:client/common/conn.dart';
import 'package:client/common/info_route.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:client/provider/app_provider.dart';
import 'package:client/provider/chatroom_msg_provider.dart';

class ChatroomTalk extends StatefulWidget {
  // const TalkRoute({super.key});
  ChatroomTalk({super.key});

  @override
  _ChatroomTalkState createState() => _ChatroomTalkState();
}

class _ChatroomTalkState extends State<ChatroomTalk> {
  final inputController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _commentFocus = FocusNode();

  @override
  void dispose() {
    _scrollController.dispose();
    _commentFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text("aaa"),
      // ),
      body: _buildView(context),
    );
  }

  sendInfo() {
    var msg = inputController.text;
    var data = {
      "msg": msg,
    };
    var payload = json.encode(data);
    Conn.send(InfoRoute.reqChatRoomSendInfo, payload);
    inputController.clear();
  }

  Widget _buildView(BuildContext context) {
    var userUuid = AppProvider.getUser().uuid;

    return Column(
      children: [
        Expanded(
            child: Container(
          padding: EdgeInsets.only(left: 30, right: 30),
          child: Consumer<ChatroomInfoProvider>(
            builder: (context, info, child) {
              var list = info.getList();

              var listView = ListView.builder(
                  itemCount: list.length,
                  controller: _scrollController,
                  itemBuilder: (context, index) {
                    var item = list[index];

                    var p = 1;
                    if (item.uuid == userUuid) {
                      p = 2;
                    }

                    return TalkItem(
                        name: item.name, content: item.msg, position: p);
                  });

              Future.delayed(Duration(milliseconds: 500), () {
                _scrollController
                    .jumpTo(_scrollController.position.maxScrollExtent);
                // _commentFocus.requestFocus();
              });

              return listView;
            },
          ),
        )),
        RawKeyboardListener(
          focusNode: FocusNode(),
          onKey: (event) {
            if (event.runtimeType == RawKeyDownEvent &&
                (event.physicalKey == PhysicalKeyboardKey.enter ||
                    event.physicalKey == PhysicalKeyboardKey.numpadEnter)) {
              sendInfo();
            }
          },
          child: Row(children: <Widget>[
            Expanded(
              child: TextField(
                controller: inputController,
                onChanged: (text) {
                  if (text.contains('\n')) {
                    inputController.text = text.replaceAll('\n', '');
                    inputController.selection = TextSelection.fromPosition(
                      TextPosition(offset: inputController.text.length),
                    );
                  }
                },
                keyboardType: TextInputType.multiline,
                maxLines: 5,
                minLines: 5,
                decoration: const InputDecoration(
                  hintText: '输入',
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  isDense: true,
                  border: OutlineInputBorder(
                    gapPadding: 0,
                    borderRadius: BorderRadius.all(Radius.circular(4)),
                    borderSide: BorderSide(
                      width: 1,
                      style: BorderStyle.none,
                    ),
                  ),
                ),
              ),
            ),
          ]),
        ),
        TextButton(
            onPressed: () {
              sendInfo();
            },
            child: Text("发送")),
      ],
    );
  }
}

class TalkItem extends StatelessWidget {
  TalkItem({required this.name, required this.content, required this.position});
  static int left = 1;
  static int right = 2;

  int position = 1;
  String name = "";
  String content = "";
  @override
  Widget build(BuildContext context) {
    var row;
    var p;
    if (this.position == left) {
      row = [
        Text(name + ":"),
        Text(content),
      ];
      p = CrossAxisAlignment.start;
    } else {
      row = [
        Text(
          name + ":",
        ),
        Container(
          child: Text(content),
          padding: EdgeInsets.only(right: 30),
        ),
      ];
      p = CrossAxisAlignment.end;
    }
    // return Expanded(
    //     child: Row(
    //   mainAxisAlignment: p,
    //   children: row,
    // ));

    return Column(
      // mainAxisAlignment: p,
      crossAxisAlignment: p,
      children: row,
    );
  }
}
